use js_sys::Array;
use log::{info, Level};
use std::rc::Rc;
use wasm_bindgen::prelude::*;
use yew::prelude::*;

mod user;
mod userInfo;
// 使用组件
use user::User;
use userInfo::{UserInfo, UserInfoAction};

#[wasm_bindgen]
pub fn alert() {
    let window = web_sys::window().unwrap();

    window.alert_with_message("alert!!").unwrap();
}

#[function_component(App)]
fn app() -> Html {
    // 需要渲染的字段
    let names = ["admin", "test", "hboot"];

    // 渲染片段
    let names = names.iter().map(|name| {
        html! {
            <p>{format!("{name}")}</p>
        }
    });
    //     .collect::<Html>();
    let is_active = use_state(|| false);
    let bool = true;

    let age = use_state(|| 30);
    let user_info = use_reducer(UserInfo::default);
    // let age = use_state_eq(|| 30);
    let change_active = {
        let is_active = is_active.clone();
        // window.alert("点击！！！");
        //
        Callback::from(move |_| {
            alert();
            is_active.set(true)
        })
    };
    // 点击更新年龄
    let update_age = {
        let age = age.clone();
        let user_info = user_info.clone();
        let cb1 = Rc::new(Callback::from(move |_| age.set(30)));
        let cb2 = Rc::new(Callback::from(move |_| {
            user_info.dispatch(UserInfoAction::UpdateAge(30))
        }));
        //
        Callback::from(move |_| {
            cb1.emit(());
            cb2.emit(());
        })
    };

    use_effect(move || {
        // 渲染完成执行
        info!("render!")
    });
    let with_age = age.clone();
    use_effect_with(with_age, move |_| {
        // 渲染完成执行
        info!("dep render!")
    });

    let mut class = Classes::from("info");
    if *is_active {
        class.push("active")
    };

    html! {
    //  <User ..user_props />
        <>
            <button onclick={change_active}>{"active"}</button>
            <h1 class={class} style="color:red;">{"hello, trunk/yew!"}</h1>
            <h2>{"good!"}</h2>
            {for names}
            {if bool{
                html!{
                    <span>{"yes"}</span>
                }
            }else{
                html!{
                    <span>{"no"}</span>
                }
            }}

           <User>
                <button onclick={update_age}>{"更新age"}</button>
                <h4>{format!("年龄：{}",*age)}</h4>
           </User>
        </>
    }
}

fn main() {
    let _ = console_log::init_with_level(Level::Debug);

    info!("render web page");

    let arr = Array::new();
    arr.push(&JsValue::from(10));
    info!("{:?}", arr.get(0).as_f64().unwrap());
    yew::Renderer::<App>::new().render();
}
